import React from "react";
import './App.css';

import 'xterm/css/xterm.css';

import { Terminal } from 'xterm';
import { FitAddon } from "xterm-addon-fit";

class T extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
        }
    }

    async componentDidMount() {

        this.term = new Terminal();

        this.term.open(document.getElementById('term'));

        var fitAddon = new FitAddon();
        this.term.loadAddon(fitAddon);
        fitAddon.fit();
        // 内容全屏显示-窗口大小发生改变时
        function resizeScreen(size) {
            // console.log("size", size);
            try {
                fitAddon.fit();
                // 窗口大小改变时触发xterm的resize方法，向后端发送行列数，格式由后端决定
                // this.term.onResize(size => {
                //     // _this.onSend({ Op: "resize", Cols: size.cols, Rows: size.rows });
                // });
            } catch (e) {
                console.log("e", e.message);
            }
        }
        window.addEventListener("resize", resizeScreen);

        

        window.ws = new WebSocket("ws://localhost:38888/ws?cId=111");
        window.ws.onopen = () => {
            window.ws.send(JSON.stringify({ type: "Conn", data: JSON.stringify({ dataId: "1" }) }));
        }

        let _term = this.term;
        window.ws.onmessage = (msg) => {
            let data = JSON.parse(msg.data);
            if (data.type == 'TerminalMsg') {
                let msg = JSON.parse(data.data).msg;
                _term.write(msg);
            }
        }

        this.term.onData(key => {
            window.ws.send(JSON.stringify({ type: "CtlMsg", data: JSON.stringify({ ctlMsg: key }) }));
        });
    }

    render() {
        return (
            <>
                <div id="term"></div>
            </>
        );
    }

}

export default T;
